﻿// WebZHX.API/Middleware/ExceptionHandlerMiddleware.cs
using Infrastructure.Services;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;

namespace API.Middleware
{
    /// <summary>
    /// 全局异常处理中间件
    /// </summary>
    public class ExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;

        public ExceptionHandlerMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, FileLoggerService loggerService)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                // 记录异常日志到文件
                loggerService.LogException(ex, "全局异常捕获", "Middleware", "ExceptionHandler");

                // 返回统一的错误响应
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                context.Response.ContentType = "application/json";

                var errorResponse = new
                {
                    success = false,
                    message = "服务器内部错误",
                    error = ex.Message,
                    traceId = context.TraceIdentifier
                };

                await context.Response.WriteAsJsonAsync(errorResponse);
            }
        }
    }
}